<template>
  <a-modal
    :title="$t('all.autotext791')"
    :visible="modalVisible"
    width="600px"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form-model
      :model="form"
      :rules="formRules"
      ref="formRef"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-model-item :label="$t('all.autotext734')" prop="pwd">
        <a-input-password v-model="form.pwd" :maxLength="30" :placeholder="$t('all.autotext1261')" />
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext168')" prop="pwdConfirm">
        <a-input-password v-model="form.pwdConfirm" :maxLength="30" :placeholder="$t('all.autotext1261')" />
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>

<script>
import { updatePassword } from '@api/system/user'

export default {
  name: 'UpdatePwdModal',
  props: {
    modalVisible: {
      type: Boolean,
      default: false
    }
  },
  data () {
    const validatorConfirmPwd = (rule, value, callback) => {
      if (this.form.pwd === this.form.pwdConfirm) {
        callback()
      } else {
        callback(new Error(this.$t('all.autotext1099')))
      }
    }
    return {
      form: {
        pwd: '',
        pwdConfirm: ''
      },
      formRules: {
        pwd: [
          { required: true, message: this.$t('all.autotext575'), trigger: 'change' },
          { pattern: /^\S*(?=\S{8,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*.? ])\S*$/, message: this.$t('all.autotext1261') }
        ],
        pwdConfirm: [
          { required: true, message: this.$t('all.autotext118'), trigger: 'change' },
          { pattern: /^\S*(?=\S{8,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*.? ])\S*$/, message: this.$t('all.autotext1261') },
          { required: true, trigger: 'blur', validator: validatorConfirmPwd }
        ]
      },
      labelCol: { span: 5 },
      wrapperCol: { span: 18 }
    }
  },
  methods: {
    handleOk () {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.updatePassword()
        }
      })
    },
    updatePassword () {
      updatePassword({ pwd: this.form.pwd })
        .then(res => {
          this.$message.success(this.$t('all.autotext1020'))
          this.handleCancel()
          // 修改密码成功 退出登录
          this.$store.dispatch('Logout').then(() => {
            this.$router.push({ name: 'login' })
          })
        })
        .catch(() => {})
    },
    // 点击取消关闭对话框并重置
    handleCancel () {
      this.$emit('cancel')
      setTimeout(() => {
        this.$refs.formRef.resetFields()
      }, 200)
    }
  }
}
</script>

<style scoped>

</style>
